package com.example.demo1.controller;


import com.alibaba.nacos.api.exception.NacosException;
import com.example.demo1.pojo.StudentCollectionPojo;
import com.example.demo1.pojo.StudentPojo;
import com.example.demo1.service.NacosConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api")
public class BController {

    @Autowired
    private NacosConfigService nacosConfigService;


    /**
     * 找出所有年龄=14岁的学生
     * http://127.0.0.1:8080/api/students/15
     *
     * @param age
     * @return
     * @throws NacosException
     */
    @GetMapping("/students/{age}")
    public List<StudentPojo> getStudentByAge(@PathVariable int age) throws NacosException {

        System.out.println("查询的学生Age=" + age);

        // 从服务中获取所有的学生配置
        StudentCollectionPojo studentCollectionPojo = nacosConfigService.getStudentCollection();

        // 一般程序员写法：
        List<StudentPojo> studentPojos = new ArrayList<StudentPojo>();

        for (StudentPojo stu : studentCollectionPojo.getStudents()) {
            if (stu.getAge() == age) {
                studentPojos.add(stu);
            }
        }


        // 高级程序员做法 。使用Stream 检索
//        List<StudentPojo> studentPojos = studentCollectionPojo.getStudents()
//                .stream().filter(s -> s.getAge() == age).collect(Collectors.toList());


        return studentPojos;
    }


}
